<?php
namespace common\service;

use yii;
class WxService
{

    public function get_user_info($redirect_url)
    {
        if (!isset($_GET['code'])){
            $baseUrl = yii::$app->params['ty_wx_url'].$redirect_url;
            Header("Location: $baseUrl");
            exit();
        } else {
            $code = $_GET['code'];
            $data = $this->GetOpenidAccessTokenFromMp($code);
            $union_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid']. '&lang=zh_CN';
            $res = self::curlGet($union_url);
            $data = json_decode($res,true);
            return $data;
        }
    }


    /**
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     * @return 返回构造好的url
     * 待用户确定状态下获取用户
     */
    private function __CreateUserForCode($redirectUrl)
    {
//        $urlObj["appid"] = yii::$app->params['wxpay_config']['appid'];//$this->appid;
//        $urlObj["redirect_uri"] = "$redirectUrl";
//        $urlObj["response_type"] = "code";
//        $urlObj["scope"] = "snsapi_userinfo";
//        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $redirectUrl;//$this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }


    /**
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * @return openid
     */
    public function GetOpenidAccessTokenFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        $res = self::curlGet($url);
        //取出openid
        $data = json_decode($res,true);
        try {
            if ($data['openid']) {
                //一天缓存
                Yii::$app->session->set(md5('openid'), $data['openid']);
            }
        } catch (\Exception $ex) {
//            $openid = str_replace('-', '', String::uuid());
//            Yii::$app->session->set(md5('openid'), $openid);
            $data['openid'] = yii::$app->session->get(md5('openid'));
        }
        return $data;
    }



    /**
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = yii::$app->params['wxpay_config']['appid'];
        $urlObj["secret"] = yii::$app->params['wxpay_config']['secret'];
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }


    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }


    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

}